//
// Package utils redis.go Redis公共函数
//
package utils

import (
	"encoding/json"
	"errors"

	"github.com/go-redis/redis"
)

// RedisClient 全局Redis Client
var RedisClient *redis.Client

// InitRedisClient 初始化Redis Client
func InitRedisClient(addr, password string, db int) error {
	client := redis.NewClient(&redis.Options{
		Addr:     addr,
		Password: password,
		DB:       db,
	})
	if err := client.Ping().Err(); err != nil {
		return err
	}
	RedisClient = client
	return nil
}

// CleanupRedisClient 关闭Redis Client
func CleanupRedisClient() error {
	return RedisClient.Close()
}

// GetIncrByKey 根据key获取自增值
func GetIncrByKey(key string) (int64, error) {
	if RedisClient == nil {
		return 0, errors.New("init incr seed error:[redis client is nil]")
	}
	cmd := RedisClient.Incr(key)
	if err := cmd.Err(); err != nil {
		return 0, err
	}
	return cmd.Val(), nil
}

// GetTypedHashItem 获取指定类型的HASH数据
func GetTypedHashItem(obj interface{}, key, filed string) error {
	resJSON, err := RedisClient.HGet(key, filed).Result()
	if err != nil {
		return err
	}
	err = json.Unmarshal([]byte(resJSON), obj)
	if err != nil {
		return err
	}
	return nil
}
